package com.czxy.controller;

import com.czxy.domain.User;
import com.czxy.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        //获取所有数据
        List<User> list = userService.findAll();
        // 使用model转存
        model.addAttribute("list", list);
        // 请求转发给list.jsp
        return "/user/list.jsp";
    }

    @RequestMapping("/findByInfo")
    public String findByInfo(User user,Model model){

        List<User> list = userService.findByInfo(user);

        model.addAttribute("list", list);
        model.addAttribute("user", user);

        return "/user/list.jsp";

    }


    @RequestMapping("/add")
    public String add(User user,Model model){

        //2.调用Service得到添加结果
        boolean rel = userService.add(user);
        //3.根据结果做出响应
        if(rel){
            //添加成功
            return "redirect:/user/findAll.action";
        }else{
            //添加失败
            model.addAttribute("message", "添加失败,登录名重复");
            model.addAttribute("user", user);
            return "/user/add.jsp";
        }
    }



    @RequestMapping("/del")
    public  String del (User user){

        userService.del(user);

        return "redirect:/user/findAll.action";

    }

    @RequestMapping("showEdit")
    public  String showEdit(Integer uid,Model model){
        User user = userService.findByUid(uid);
        model.addAttribute("user",user);
        return "/user/edit.jsp";
    }

    @RequestMapping ("/edit")
    public  String edit(User user,Model model){

        boolean rel = userService.update(user);

        if (rel){
            //修改成功
            return "redirect:/user/findAll.action";
        }else{
            //修改失败
            model.addAttribute("user",user);
            model.addAttribute("message","修改失败");
            return "/user/edit.jsp";

        }
    }



}
